
package com.demo.menu;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.demo.util.PropertiesHelper;
import com.demo.util.Upload;
import com.demo.vo.ResultVO;
import com.jfinal.aop.Before;
import com.jfinal.core.Const;
import com.jfinal.core.Controller;
import com.jfinal.core.JFinal;
import com.jfinal.kit.JsonKit;
import com.jfinal.kit.StringKit;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.render.JsonRender;
import com.jfinal.weixin.sdk.api.AccessTokenApi;
import com.jfinal.weixin.sdk.api.ApiResult;
import com.jfinal.weixin.sdk.api.MenuApi;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;

public class WxMenuController extends Controller {

	private static String AppId = "";

	static {
		Properties r = PropertiesHelper.loadProperty("/weixin.properties");
		if (!r.isEmpty()) {
			try {
	
				AppId = r.getProperty("AppId");

			} catch (Exception e) {
				Logger.getLogger(WxMenuController.class).error("无法读取参数", e);
			}
		} else {
			Logger.getLogger(WxMenuController.class).error("无法读取 weixin.properties");
		}
	}
	
    public void index() {
        render("/WEB-INF/view/weixin/menu/index.html");
    }
/**
 * add
 */
    public void  newModes() {
    String   id=getPara("id");
    String pid=getPara("pid");
//    List<Record> newlist = Db.find("select  * from     where    id=  '" + id + "'");
    List<Record> newlist =  WxMenu.dao.findAlls(  "       id=  '" + id + "'") ;

    setAttr("newlist", newlist);
    setAttr("pid",pid);
    setAttr("id",id);
    setAttr("AppId",AppId);
    render("/WEB-INF/view/weixin/menu/wxMenu_form.html");

    }

   /**
     * 在增加了SearchSql拦截之后就可以根据页面配置信息
     * 自动装配查询语句放入request中,通过getAttr(Const.SEARCH_SQL)函数获得
     * 根据实际需要自动组装到Sql语句里面
     */
	public void query() {
        int pageNumber = getParaToInt("page");
        int pageSize = getParaToInt("rows");
        Page<WxMenu> page = WxMenu.dao.page(pageNumber, pageSize, "");
        renderJson(page);
	}


    public void  getMenuTree() {
        String   id=getPara("pid");
        String yxbz=getPara("yxbz") ;
        String where="";
        if(StringKit.notBlank(yxbz)){
            where += " where yxbz =" + yxbz+"  ";
        }
        List<Record> newlist =   WxMenu.dao.findtree(where);
        JSONObject jo1 = new JSONObject();
        /// 增加根节点
        jo1.put("id", "0");
        jo1.put("pId", "0");
        jo1.put("name", "根节点");
        JSONArray jsonArr = new JSONArray();
        if (newlist.size()==0){
            jsonArr.add(jo1);
            renderJson(jsonArr);
        }  else {
            for(int j=0;j<newlist.size();j++){
                JSONObject jo = new JSONObject();
                jo.put("id",  newlist.get(j).get("id"));
                jo.put("pId", newlist.get(j).get("pId"));
                jo.put("name",  newlist.get(j).get("name"));
                jsonArr.add(jo);
            }
            jsonArr.add(jo1);
        }
        System.out.println(jsonArr);
        renderJson(jsonArr);

    }
	/**
     * save
     * @param
     * @return
     */
	public void save() {
        if(getModel(WxMenu.class).save()){
    //        renderJson("保存成功");
			render(new JsonRender(JsonKit.toJson("保存成功！")).forIE());

        }else{
        //    renderJson("保存失败");
			render(new JsonRender(JsonKit.toJson("保存失败！")).forIE());

        }
	}
	
/**
     * Post请求的菜单更新函数,可以接受菜单的id和菜单对象,并且根据菜单id进行更新,返回影响行数根据此判断是否操作成功
     * 本例子使用rose框架的est风格url可以吧参数作为路径一部分进行传递
     * @param
     * @return
     */
	public void update() {
        if(getModel(WxMenu.class).update()){
         //   renderJson("修改成功");
			render(new JsonRender(JsonKit.toJson("修改成功！")).forIE());

        }else{
           // renderJson("修改失败");
			render(new JsonRender(JsonKit.toJson("修改失败！")).forIE());

        }
	}
	
		/**
     * Post请求的菜单删除函数,可以接受菜单ID 并且根据ID进行物理删除,并且返回影响行数,据此判断是否操作成功
     * @param
     * @return
     */
	public void delete() {

        String where = " pid=  '"+getPara("wxMenu.id")+"'";
        List<Record> newlist =   WxMenu.dao.findAlls(where);
        if(newlist.size() >0){
        //    renderJson("请删除子节点!");
			render(new JsonRender(JsonKit.toJson("请删除子节点!")).forIE());

        }else {
            if(WxMenu.dao.deleteById(getPara("wxMenu.id"))){
         //       renderJson("删除成功！");
    			render(new JsonRender(JsonKit.toJson("删除成功！")).forIE());

            }else{
             //   renderJson("删除失败！");
    			render(new JsonRender(JsonKit.toJson("删除失败！")).forIE());

            }
        }

	}


   /**
     * 创建自定义菜单
     */
    public void setMenu()
    {
        String menus="{\"button\":[";
        String menua="";
        MenuApi menuApi=new MenuApi();
        //ApiResult apiResult = menuApi.createMenu("{type: 'view',name: '点餐',url: 'http://loveyy.gnjsp.xzbiz.cn/_front/main.html/',sub_button: [ ]},{type: 'view',name: '我的订单',url: 'http://www.baidu.com',sub_button: [ ]},{type: 'view',name: '其他',url: 'http://www.baidu.com',sub_button: [ ]}]}}");
        List<Record> newlist =   WxMenu.dao.findbymenu(" where level=1");
        List<Record> articleList = new ArrayList<Record>();
        Map articles = new HashMap();
        for ( int i=0;i<newlist.size();i++){
            Record article = new Record();
            String name=   newlist.get(i).get("name");
            String id=   newlist.get(i).get("id").toString();
            String type=   newlist.get(i).get("type");
            String key=   newlist.get(i).get("key");
            String url=   newlist.get(i).get("url");
       
            String num=   newlist.get(i).get("num").toString();
            if( !num.equals("0")){
                List<Record> newlists =   WxMenu.dao.findbymenu(" where level=2  and pid= '"+id+"'");
                List<Record> articleLista = new ArrayList<Record>();
                article.set("name", name);
                for ( int j=0;j<newlists.size();j++){
                    Record articlea = new Record();
                    String names=   newlists.get(j).get("name");
                                String ids=   newlists.get(j).get("id").toString();
                                String types=   newlists.get(j).get("type");
                                String keys=   newlists.get(j).get("key");
                                String urls=   newlists.get(j).get("url");
                                String nums=   newlists.get(j).get("num").toString();
                    articlea.set("name", names);
                    if (types.equals("click")){
                        articlea.set("type", types);
                        articlea.set("key", keys);
                    } else if (types.equals("view")){
                        articlea.set("type", types);
                        articlea.set("url", urls);
                    }
                    articleLista.add(articlea);
                    System.out.println("============"+articlea);
                }
                article.set("sub_button", articleLista);
                }   else {
                article.set("name", name);
                        if (type.equals("click")){
                            article.set("type", type);
                            article.set("key", key);
                        } else if (type.equals("view")){
                            article.set("type", type);
                            article.set("url", url);
                        }
            }
            articleList.add(article);
        }
        articles.put("button", articleList);
//        System.out.println(menus);
        String data = JsonKit.toJson(articles);
          System.out.println(data);
        ApiResult apiResult = menuApi.createMenu(data);
        System.out.println("======================"+ AccessTokenApi.getAccessToken().getAccessToken());
        System.out.println("======================"+apiResult.getErrorCode());
        System.out.println("======================"+apiResult.getErrorMsg());
        renderText(apiResult.getErrorMsg());
    }
    
}

